package cn.community.care.module.system.service.chat;

import cn.community.care.framework.common.exception.ServiceException;
import cn.community.care.module.system.dal.dataobject.hotproducts.HotProductsDO;
import cn.community.care.module.system.dal.mysql.hotproducts.HotProductsMapper;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService{

    @Value("${aigc.apiKey}")
    private  String apiKey ;

    @Resource
    private HotProductsMapper hotProductsMapper;

    public  GenerationResult callWithMessage(String content) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
    @Override
    public String chat(String content) {
        GenerationResult result = null;
        if (content.contains("商品推荐")){
            List<HotProductsDO> list = hotProductsMapper.selectList();
            content = content.replace("商品推荐","");
            content = "请把下面这几个按照换行的方式回答出来，并且你直接介绍推荐理由"+"1:"+list.get(0).getTitle()+"2:"+list.get(1).getTitle()+"3:"+list.get(2).getTitle()+"4:"+list.get(3).getTitle();
        }
        try {
            result = callWithMessage(content);
            System.out.println();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            throw new ServiceException(500, e.getMessage());
        }
        return result.getOutput().getChoices().get(0).getMessage().getContent();
//        return "hello" ;
    }
}
